import React, { Component, useState } from "react";
import { Link, Route, Switch, Redirect, Prompt } from "react-router-dom";

class Home extends Component {
  render() {
    return <div>这是首页页面</div>;
  }
}

const About = () => {
  return <div>这是关于页面</div>;
};

const Form = () => {
  const [text, setText] = useState("");
  const fn = (v) => {
    setText(v.target.value);
  };
  return (
    <>
      <input type="text" value={text} onChange={fn} />
      <button>清空</button>
      <Prompt
        when={text !== ""}
        message={(location) =>
          `Are you sure you want to go to ${location.pathname}`
        }
      />
    </>
  );
};

class App extends Component {
  render() {
    return (
      <>
        <h2>路由保护</h2>
        <ul>
          <li>
            <Link to="/home">首页</Link>
          </li>
          <li>
            <Link to="/about">关于页</Link>
          </li>
          <li>
            <Link to="/form">表单页</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Redirect from="/" to="/home" exact></Redirect>
          <Route path="/home" component={Home}></Route>
          <Route path="/about" component={About}></Route>
          <Route path="/form" component={Form}></Route>
        </Switch>
      </>
    );
  }
}

export default App;
